// 选择到文件（纯数据、绘图）

import React, { Component } from 'react';
import { Form, TreeSelect, message } from 'antd';
import './modal.css';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import { reqProcessOrgList,reqProcessWsList,reqProcessDrillList,reqProcessDocList } from '../../api';

//const orgList = [{org_id: 'org1' ,org_name: '组织1',type:'org'},{org_id: 'org2' ,org_name: '组织2',type:'org'},{org_id: 'org3' ,org_name: '组织3',type:'org'}]
//const wsList = [{ws_id: 'ws1' ,ws_name: '工区1',type:'ws'},{ws_id: 'ws2' ,ws_name: '工区2',type:'ws'},{ws_id: 'ws3' ,ws_name: '工区3',type:'ws'}]
//const drillList = [{drill_id: 'dril1' ,drill_name: '井1',type:'drill'},{drill_id: 'dril2' ,drill_name: '井2',type:'drill'},{drill_id: 'dril3' ,drill_name: '井3',type:'drill'}]
const docList = [{doc_id:'doc1',title:'文件1',type:'doc',doc_type:'纯数据文件'},{doc_id:'doc2',title:'文件2',type:'doc',doc_type:'纯数据文件'},]


class SelectFileForm extends Component {   
  
  static propTypes = {
    setForm: PropTypes.func.isRequired,
    setDocList: PropTypes.func.isRequired,
  };

  formRef = React.createRef();          
      
  state = {
    value: undefined,
    drill_org_id:'', // 当前用户选中的组织id
    drill_ws_id:'',  // 当前用户选中的工区id
    treeData: [],    // 已进入页面先加载 组织   { id: 1, pId: 0, value: '1', title: '组织1' },
  };

  getOrg = async() => {    // 页面加载时，获取组织信息 
    const org_pid = this.props.user.org.org_id;
    const result = await reqProcessOrgList(org_pid); 
    //console.log("获取组织",result)
    if(result.code === 200){
      const orgList = result.data;
      const treeData = [];
      orgList.map((item) => {
        return treeData.push({id: item.org_id ,pId:'0', value: item.org_id, title: item.org_name, selectable: false, type: item.type})   // item.org_id
      })
      this.setState({
        treeData
      })
    }else{
      message.error(result.data)
    } 
  }

  genTreeNode = (nodePid,Node,isLeaf = false) => {  // 获取数据后，转换格式  3！！！！！！！
    //console.log("genTreeNode", Node )
    return {
      id: Node.ws_id || Node.drill_id || Node.doc_id,
      pId: nodePid,
      value: Node.ws_id || Node.drill_id || Node.doc_id,
      title: Node.ws_name || Node.drill_id || Node.title,
      selectable: isLeaf ? true : false,
      type: Node.type,
      isLeaf
    };   
  };

  onLoadData = async(treeNode) =>{    // 异步加载数据   2！！！！！！
    const nodePid = treeNode.pId;
    const type = treeNode.type;
    if(type === "org"){          // 点击组织，获取工区
      const ws_pid = treeNode.id;
      this.setState({ drill_org_id: ws_pid})
      const result = await reqProcessWsList(ws_pid);
      console.log("获取工区",result);
      if(result.code === 200){
        const wsList = result.data;
        this.setState({       //渲染新增节点
          treeData: this.state.treeData.concat(
            wsList.map((item) => {
              return this.genTreeNode(ws_pid,item)
            })  
          ),
        });
        // new Promise(resolve => {
        //   setTimeout(() => {
        //     this.setState({       //渲染新增节点
        //       treeData: this.state.treeData.concat(
        //         wsList.map((item) => {
        //           return this.genTreeNode(ws_pid,item)
        //         })  
        //       ),
        //     });
        //     resolve();
        //   }, 200);
        // }); 
      }else {
        message.error(result.data)
      } 
    }else if(type === "ws"){                // 点击工区，获取井
      const drill_org_id = this.state.drill_org_id;
      const drill_ws_id = treeNode.id;
      this.setState({ drill_ws_id })
      const result = await reqProcessDrillList(drill_org_id,drill_ws_id);
      console.log("获取钻井",result);
      if(result.code === 200){
        const drillList = result.data;
        this.setState({       //渲染新增节点
          treeData: this.state.treeData.concat(
            drillList.map((item) => {
              return this.genTreeNode(drill_ws_id,item)   // drill_pid: drill_ws_id
            })  
          ),
        });
        // new Promise(resolve => {
        //   setTimeout(() => {
        //     this.setState({       //渲染新增节点
        //       treeData: this.state.treeData.concat(
        //         drillList.map((item) => {
        //           return this.genTreeNode(drill_ws_id,item)   // drill_pid: drill_ws_id
        //         })  
        //       ),
        //     });
        //     resolve();
        //   }, 200);
        // });
      }else{
        message.error(result.data);
      }   
    }else if(type === "drill"){            // 点击井，获取文件
      const drill_id = treeNode.id;
      const org_id = this.state.drill_org_id;
      const ws_id = this.state.drill_ws_id;
      const result = await reqProcessDocList(drill_id,org_id,ws_id);
      console.log("获取文件",result)
      if(result.code === 200){
        var docList = []
        result.data.map((item) => {
          let item1 = {
            doc_id: item.doc_id,
            title: item.title,
            type: item.type,
          }
          docList.push(item1)
        })
        this.setState({       //渲染新增节点
          treeData: this.state.treeData.concat(
            docList.map((item) => {
              return this.genTreeNode(drill_id,item,true)  
            })  
          ),
        });
        // const docList = result.data;
        // new Promise(resolve => {
        //   setTimeout(() => {
        //     this.setState({       //渲染新增节点
        //       treeData: this.state.treeData.concat(
        //         docList.map((item) => {
        //           return this.genTreeNode(drill_id,item,true)  
        //         })  
        //       ),
        //     });
        //     resolve();  
        //   }, 200);
        // });
        this.props.setDocList(result.data);   // docList  将井下的文件列表传给父组件用于匹配
      }else{
        message.error(result.data);
      } 
    }  
  }

  onChange = value => {  // 最后选中的文件id  4！！！！！！！
    //console.log("onChange",value);
    this.setState({ value });
  };

  componentWillMount(){  // 1、页面载入时，获取组织
    this.getOrg();
  }
  componentDidMount() {
    this.props.setForm(this.formRef);
  }

  render() {
    const { treeData } = this.state;
    return (
      <Form 
        ref={this.formRef}   
        name="control-ref"  
        onFinish={this.onFinish}  
      >    
        <Form.Item 
          name="doc_id" 
          label="选择文件" 
          rules={[{ required: true }]}
        >
          <TreeSelect
            treeDataSimpleMode  // 使用简单格式的treedata
            style={{ width: '100%' }}
            value={this.state.value}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择"
            onChange={this.onChange}    //选中树节点时调用此函数，最后一步，选中文件
            loadData={this.onLoadData}   // 异步加载数据
            treeData={treeData}
          />
        </Form.Item>
      </Form>
    );
  }
}

export default connect(
  state => ({user: state.user, }),
  {}
)(SelectFileForm);